package qyWechat

import (
	"io/ioutil"
	"net/http"
)

type Context interface {
	Wechat() *QyWechat
	Request() Request
	Response() Response
}

type Request interface {
	ToUserName() string
	FromUserName() string
	CreateTime() int
	MsgType() string
	Content() string
	Event() string
	EventKey() string
	ChangeType() string
	MsgId() int
	AgentID() int
	ResponseCode() string

	UserID() string
	NewUserID() string
	Name() string
	Position() string
	Mobile() string
	Gender() int
	Status() int
	Avatar() string
	TaskId() string
}
type Response interface {
	Success() error
	Text(content string) error
}

type context struct {
	wx *QyWechat
	w  http.ResponseWriter
	r  *http.Request
	f  *defaultRequestMessage
	t  defaultResponse
}

func newContext(w http.ResponseWriter, r *http.Request, wx *QyWechat) (c *context, err error) {
	c = &context{
		wx: wx,
		w:  w,
		r:  r,
		f:  &defaultRequestMessage{},
	}
	c.t = defaultResponse{c: c, w: w}
	err = c.parse()
	return
}
func (c *context) Wechat() *QyWechat {
	return c.wx
}
func (c *context) Request() Request {
	return c.f
}
func (c *context) Response() Response {
	return c.t
}

func (c *context) parse() (err error) {
	defer c.r.Body.Close()
	data, err := ioutil.ReadAll(c.r.Body)
	if err != nil {
		return
	}
	// 解密请求的数据
	msgSignature := c.r.URL.Query().Get("msg_signature")
	timestamp := c.r.URL.Query().Get("timestamp")
	nonce := c.r.URL.Query().Get("nonce")
	data, err = c.wx.DecryptMsg(msgSignature, timestamp, nonce, data)
	if err != nil {
		return err
	}
	// 解析请求的数据
	return c.f.Unmarshal(data)
}
